<template>
  <view class="van-tabs">
    <!-- 标签栏 -->
    <view
      class="van-tabs__nav"
      :class="{ 'van-tabs__nav--scrollable': scrollable }"
    >
      <scroll-view
        v-if="scrollable"
        class="van-tabs__scroll"
        scroll-x
        show-scrollbar="false"
        :scroll-with-animation="true"
      >
        <view class="van-tabs__nav-wrap">
          <slot name="nav-left"></slot>
          <view
            v-for="(tab, index) in tabs"
            :key="index"
            class="van-tab"
            :class="{
              'van-tab--active': currentIndex === index,
              'van-tab--disabled': tab.disabled,
            }"
            @click="handleClick(index)"
            :style="{ width: fixedWidth ? `${fixedWidth}px` : '' }"
          >
            <text class="van-tab__text">{{ tab.name }}</text>
            <view
              v-if="tab.badge"
              class="van-tab__badge"
              :class="{ 'van-tab__badge--dot': tab.badge === true }"
            >
              {{ tab.badge !== true ? tab.badge : "" }}
            </view>
          </view>
          <slot name="nav-right"></slot>
        </view>
      </scroll-view>

      <!-- 非滚动模式 -->
      <view v-else class="van-tabs__nav-wrap">
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          class="van-tab"
          :class="{
            'van-tab--active': currentIndex === index,
            'van-tab--disabled': tab.disabled,
          }"
          @click="handleClick(index)"
          :style="{ flex: fixedWidth ? `0 0 ${fixedWidth}px` : 1 }"
        >
          <text class="van-tab__text">{{ tab.name }}</text>
          <view
            v-if="tab.badge"
            class="van-tab__badge"
            :class="{ 'van-tab__badge--dot': tab.badge === true }"
          >
            {{ tab.badge !== true ? tab.badge : "" }}
          </view>
        </view>
      </view>

      <!-- 下划线 -->
      <view
        class="van-tabs__line"
        :style="{
          width: lineWidth,
          transform: `translateX(${lineLeft})`,
          transition: `all ${duration}ms ${easingFunction}`,
        }"
      ></view>
    </view>

    <!-- 内容区域 -->
    <view class="van-tabs__content" :style="{ height: contentHeight }">
      <view
        class="van-tabs__content-wrap"
        :style="{
          transform: `translateX(-${currentIndex * 100}%)`,
          transition: `transform ${duration}ms ${easingFunction}`,
        }"
      >
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          class="van-tab__pane"
          :class="{ 'van-tab__pane--active': currentIndex === index }"
          :style="{ width: `100%` }"
        >
          <slot :name="`pane-${index}`">{{ tab.content }}</slot>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "VanTabs",
  props: {
    // 标签数据 [{ title: '标签1', content: '内容1', badge: 3, disabled: false }]
    tabs: {
      type: Array,
      required: true,
      default: () => [],
    },
    // 默认选中索引
    defaultIndex: {
      type: Number,
      default: 0,
    },
    // 是否可滚动
    scrollable: {
      type: Boolean,
      default: false,
    },
    // 固定标签宽度
    fixedWidth: {
      type: Number,
      default: 0,
    },
    // 内容区域高度
    contentHeight: {
      type: String,
      default: "auto",
    },
    // 动画时长(ms)
    duration: {
      type: Number,
      default: 300,
    },
    // 动画缓动函数
    easingFunction: {
      type: String,
      default: "cubic-bezier(0.34, 1.56, 0.64, 1)",
    },
  },
  data() {
    return {
      currentIndex: this.defaultIndex,
      lineWidth: "0px",
      lineLeft: "0px",
      tabRects: [],
    };
  },
  watch: {
    defaultIndex(val) {
      this.currentIndex = val;
      this.updateLineStyle();
    },
    currentIndex(val) {
      this.updateLineStyle();
      this.scrollToActiveTab();
      this.$emit("change", val);
    },
    tabs() {
      this.$nextTick(() => {
        this.updateLineStyle();
      });
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.updateLineStyle();
    });

    // 监听窗口变化
    uni.onWindowResize(() => {
      this.$nextTick(() => {
        this.updateLineStyle();
      });
    });
  },
  beforeUnmount() {
    uni.offWindowResize();
  },
  methods: {
    // 点击标签
    handleClick(index) {
      const tab = this.tabs[index];
      if (tab.disabled || this.currentIndex === index) return;
      this.currentIndex = index;
    },

    // 更新下划线样式
    updateLineStyle() {
      const query = uni.createSelectorQuery().in(this);
      query
        .selectAll(".van-tab")
        .boundingClientRect((data) => {
          if (data && data.length) {
            this.tabRects = data;
            const activeRect = data[this.currentIndex];
            if (activeRect) {
              this.lineWidth = `${activeRect.width}px`;
              this.lineLeft = `${activeRect.left - data[0].left}px`;
            }
          }
        })
        .exec();
    },

    // 滚动到激活的标签（滚动模式下）
    scrollToActiveTab() {
      if (!this.scrollable || !this.tabRects.length) return;

      const query = uni.createSelectorQuery().in(this);
      query
        .select(".van-tabs__scroll")
        .boundingClientRect((scrollRect) => {
          const activeRect = this.tabRects[this.currentIndex];
          if (scrollRect && activeRect) {
            // 计算滚动位置，确保激活标签在可视区域
            const scrollLeft =
              activeRect.left -
              scrollRect.left +
              this.$refs.scroll.scrollLeft -
              scrollRect.width / 2 +
              activeRect.width / 2;
            this.$refs.scroll.scrollTo({
              left: scrollLeft,
              duration: this.duration,
            });
          }
        })
        .exec();
    },
  },
};
</script>

<style scoped>
.van-tabs {
  width: 100%;
  overflow: hidden;
  background-color: #fff;
}

/* 导航栏样式 */
.van-tabs__nav {
  position: relative;
  display: flex;
  height: 44px;
  border-bottom: 1px solid #eee;
  box-sizing: border-box;
}

.van-tabs__nav--scrollable {
  overflow: hidden;
}

.van-tabs__scroll {
  flex: 1;
  height: 100%;
}

.van-tabs__nav-wrap {
  display: flex;
  height: 100%;
}

/* 标签样式 */
.van-tab {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 0 16px;
  font-size: 14px;
  position: relative;
  box-sizing: border-box;
  cursor: pointer;
}

.van-tab--disabled {
  color: #c9c9c9;
  cursor: not-allowed;
}

.van-tab__text {
  transition: color 0.3s;
}

.van-tab--active .van-tab__text {
  color: #1989fa;
  font-weight: 500;
}

/* 徽章样式 */
.van-tab__badge {
  margin-left: 4px;
  padding: 0 4px;
  min-width: 16px;
  height: 16px;
  font-size: 12px;
  line-height: 16px;
  color: #fff;
  background-color: #ee0a24;
  border-radius: 8px;
  white-space: nowrap;
}

.van-tab__badge--dot {
  width: 8px;
  height: 8px;
  padding: 0;
  min-width: auto;
  border-radius: 50%;
}

/* 下划线样式 */
.van-tabs__line {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 2px;
  background-color: #1989fa;
  border-radius: 1px;
}

/* 内容区域样式 */
.van-tabs__content {
  overflow: hidden;
  position: relative;
}

.van-tabs__content-wrap {
  display: flex;
  height: 100%;
}

.van-tab__pane {
  flex-shrink: 0;
  box-sizing: border-box;
  height: 100%;
}

.van-tab__pane--active {
  display: block;
}
</style>
